var gulp = require('gulp')

var webserver = require('gulp-webserver')

var sass = require('gulp-sass')

var webpack = require('gulp-webpack')

var named = require('vinyl-named')

// 启动 webserver
gulp.task('webserver', function () {
  gulp.src('./dev')
    .pipe(webserver({
      host: 'localhost',
      port: 4000,
      directoryListing: {
        enable: true,
        path: './dev'
      },
      livereload: true
    }))
})

// copyhtml
gulp.task('copyhtml', function () {
  gulp.src('./src/*.html')
    .pipe(gulp.dest('./dev/'))
})

// copyimage
gulp.task('copyimage', function () {
  gulp.src('./src/images/**/*')
    .pipe(gulp.dest('./dev/images'))
})

// 编译scss
gulp.task('packscss', function () {
  gulp.src('./src/styles/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./dev/styles'))
})

// 引入gulp-webpack, 实现CommonJS 模块化开发
gulp.task('packjs', function () {
  gulp.src('./src/scripts/app.js')
    .pipe(named())
    .pipe(webpack({
      output: {
        filename: '[name].js'
      },
      module: {
        loaders: [
          {
            test: /\.js$/,
            loader: 'imports-loader',
            exclude: './node_modules'
          },
          {
            test: /\.string$/,
            loader: 'string-loader'
          }
        ]
      }
    }))
    .pipe(gulp.dest('./dev/scripts'))
})

gulp.task('watch', function () {
  gulp.watch('./src/styles/**/*.scss', ['packscss'])
  gulp.watch('./src/scripts/**/*.js', ['packjs'])
  gulp.watch('./src/templates/**/*.string', ['packjs'])
  gulp.watch('./src/*.html', ['copyhtml'])
  gulp.watch('./src/images/**/*', ['copyimage'])
})

gulp.task('default', ['webserver', 'packscss', 'packjs', 'copyhtml', 'copyimage', 'watch'], function () {
  console.log('done.')
})
